import {
    isArray,
    removeItemInArray,
    isFun,
    debounce
} from './utils';


class Subscribe {
    constructor() {
        this.subscribers = [];
        this.events = {};
    }

    _debouncepub = debounce(function (type, data) {
        let events = this.events[type];
        if (isArray(events)) {
            events.forEach(function (subEvent) {
                isFun(subEvent) && subEvent(data);
            });
        }
    }, 200)

    publish(type, data) {
        // this._debouncepub(type, data);
        let events = this.events[type];
        if (isArray(events)) {
            events.forEach(function (subEvent) {
                isFun(subEvent) && subEvent(data);
            });
        }
    }

    subscribe(type, cb) {
        let t = setTimeout(() => {
            if (isArray(this.events[type])) {
                this.events[type].push(cb);
            } else {
                this.events[type] = [cb];
            }
            clearTimeout(t);
        }, 0);
    }

    fire(type, cb) {
        if (isArray(this.events[type])) {
            this.events[type] = removeItemInArray(cb, this.events[type]);
        }
    }

}

export default Subscribe;